function topKFrequent(nums, k) {
  let freqMap = new Map()
  const bucket = [], result = []
  for (let num of nums) {
    freqMap.set(num, (freqMap.get(num) || 0) + 1)
  }
  for (let [num, freq] of freqMap) {
    bucket[freq] = (bucket[freq] || new Set()).add(num)
  }
  for (let i = bucket.length; i >= 0; i--) {
    if (bucket[i]) {
      result.push(...bucket[i])
    }
    if (result.length === k) {
      break
    }
  }
  return result
}